package io.elegant.sessions.widgets

import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.google.protobuf.Any
import io.elegant.ElegantApiGrpc
import io.elegant.sessions.BaseSession
import io.elegant.toActivity
import io.elegant.widgets.BaseWidget
import kotlin.reflect.KClass

abstract class BaseWidgetSession<V: View, T: BaseWidget<V>>(
    stub: ElegantApiGrpc.ElegantApiStub,
    private val context: Context
): BaseSession(stub, context) {
    abstract val clazz: KClass<V>
    abstract val widgetClazz: KClass<T>
    private var layout: ViewGroup? = null
    private var widget: T? = null
    override fun onCreate(sessionId: Long, futureId: Long, vararg argv: Any) {
        layout = context.toActivity()?.getViewGroup()
        widget = widgetClazz.constructors.first().call(this, layout!!, csMain).apply {
            create(clazz, sessionId, futureId, *argv)
        }
        super.onCreate(sessionId, futureId, *argv)
    }
    override fun onDestroy() {
        widget?.destroy()
        widget = null
        super.onDestroy()
    }
    override suspend fun onReceive(name: String, sessionId: Long, futureId: Long, vararg argv: Any) {
        if (widget?.onReceive(name, sessionId, futureId, *argv) == true) return
        super.onReceive(name, sessionId, futureId, *argv)
    }
}